package lockDemo;
import org.apache.log4j.Logger;

import java.lang.management.ManagementFactory;
import java.lang.management.RuntimeMXBean;
import java.nio.channels.FileChannel;
import java.nio.channels.FileLock;
import java.io.RandomAccessFile;
import java.io.File;

/**
 * @author Ajie
 * @date 2023/8/12
 * @function
 * idea 配置
 */
public class ProcessLock_进程锁_Example {
    private static final Logger logger = Logger.getLogger(ProcessLock_进程锁_Example.class);

        public static void main(String[] args) {
            File file = new File("lockfile.txt");
            for (int i = 0; i < 10; i++) {
                try (RandomAccessFile raf = new RandomAccessFile(file, "rw");
                     FileChannel channel = raf.getChannel()) {
                    logger.info(": 进程" + getProcessID()+"等待锁");
                    FileLock lock = channel.lock(); // 获取文件锁
                    logger.info(": 进程"  +getProcessID()+ "获取了锁---");
                    Thread.sleep(5000); // 模拟进程持有锁的操作
                    lock.release(); // 释放文件锁
                    logger.info(": 进程" +getProcessID()+ "释放了锁");
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }

        }

    public static final int getProcessID() {
        RuntimeMXBean runtimeMXBean = ManagementFactory.getRuntimeMXBean();
//        System.out.println(runtimeMXBean.getName());
        return Integer.valueOf(runtimeMXBean.getName().split("@")[0])
                .intValue();
    }

}


